/*
 * Copyright 2022 CloudWeGo Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package meta

import (
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"regexp"

	"github.com/cloudwego/hertz/cmd/hz/util/logs"
	gv "github.com/hashicorp/go-version"
)

const ManifestFile = ".hz"

type Manifest struct {
	Version *gv.Version
}

var GoVersion *gv.Version

func init() {
	// valid by unit test already, so no need to check error
	GoVersion, _ = gv.NewVersion(Version)
}

var regVersion = regexp.MustCompile(`hz version: v([0-9a-z.]*)`)

func (manifest *Manifest) Validate(dir string) error {
	rd, err := ioutil.ReadFile(filepath.Join(dir, ManifestFile))
	if err != nil {
		return err
	}

	ms := regVersion.FindSubmatchIndex(rd)
	if len(ms) != 4 || ms[2] < 19 {
		logs.Errorf("Invalid manifest file: %s, pattern '%s' not match\n", filepath.Join(dir, ManifestFile), regVersion.String())
		return fmt.Errorf("current project doesn't belong to hertz framework")
	}
	v, err := gv.NewVersion(string(rd[ms[2]:ms[3]]))
	if err != nil {
		return err
	}
	*manifest = Manifest{
		Version: v,
	}
	return nil
}

func (manifest Manifest) String() string {
	return `// Code generated by hz. DO NOT EDIT.

hz version: v` + manifest.Version.String() + "\n"
}

func (manifest Manifest) Persist(dir string) error {
	file := filepath.Join(dir, ManifestFile)
	fd, err := os.OpenFile(file, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, os.FileMode(0o644))
	if err != nil {
		return err
	}
	defer fd.Close()
	_, err = fd.WriteString(manifest.String())
	return err
}
